import themeChangeBehavior from 'tdesign-miniprogram/mixins/theme-change';
const pagePermissionMixin = require('../../utils/page-permission-mixin.js');
const { MODULES } = require('../../utils/permission.js');
const { getTodayEntryList } = require('../../utils/piecework-entry-api.js');
const { pageOptimizationMixin } = require('../../utils/page-optimization-mixin.js');

Page({
  behaviors: [themeChangeBehavior],
  
  // 混入权限检查方法和性能优化
  ...pagePermissionMixin,
  ...pageOptimizationMixin,
  
  data: {
    ...pageOptimizationMixin.data,
    userInfo: null,
    selectedDate: '',
    entryList: [],
    statistics: {
      totalCount: 0,
      totalAmount: '0.00',
      approvedCount: 0,
      pendingCount: 0,
      rejectedCount: 0
    },
    loading: false,
    showDetailModal: false,
    selectedItem: null,
    pageTitle: '今日录入',
    showDirectReportButton: true, // 控制直报按钮的显示
    fromPage: '', // 记录来源页面
    lastLoadTime: null, // 上次加载时间
    dataCache: {} // 数据缓存
  },

  onLoad(options) {
    // 使用优化的页面加载
    this.onLoadOptimized('piecework-today', () => {
      // 检查页面权限
      this.onPageLoadPermissionCheck(MODULES.PIECEWORK_ENTRY);
      
      // 处理页面参数
      this.handlePageOptions(options);
      
      // 加载关键数据
      this.loadEssentialData();
    });
  },

  onReady() {
    // 使用优化的页面准备完成
    this.onReadyOptimized(() => {
      this.loadSecondaryData();
    });
  },

  onShow() {
    // 使用优化的页面显示
    this.onShowOptimized(() => {
      this.smartRefreshData();
    });
  },

  onUnload() {
    // 使用优化的页面卸载
    this.onUnloadOptimized();
  },

  // 处理页面参数
  handlePageOptions(options) {
    // 记录来源页面
    if (options.from) {
      this.setData({ fromPage: options.from });
    }
    
    // 如果有日期参数，使用传入的日期；否则使用今天
    if (options.date) {
      this.setData({ 
        selectedDate: options.date,
        pageTitle: this.formatDateTitle(options.date),
        showDirectReportButton: false // 从其他页面跳转过来查看详情时隐藏直报按钮
      });
    } else {
      this.initDate();
      this.setData({ 
        pageTitle: '今日录入',
        showDirectReportButton: true // 正常进入页面时显示直报按钮
      });
    }
  },

  // 加载关键数据
  async loadEssentialData() {
    try {
      // 先加载用户信息
      this.loadUserInfo();
      
      // 然后加载录入列表数据
      await this.loadTodayEntryListWithOptimization();
      
      // 关键数据加载完成
      this.markPageReady();
      
    } catch (error) {
      console.error('今日录入关键数据加载失败:', error);
      this.markPageError(error);
    }
  },

  // 加载次要数据
  loadSecondaryData() {
    // 延迟加载统计数据等次要信息
  },

  /**
   * 智能刷新数据 - 只在必要时重新加载
   */
  smartRefreshData() {
    const { lastLoadTime, selectedDate } = this.data;
    const now = Date.now();
    const CACHE_DURATION = 2 * 60 * 1000; // 2分钟缓存时间
    
    // 如果没有加载过数据，或者超过缓存时间，或者日期变了，则重新加载
    if (!lastLoadTime || 
        (now - lastLoadTime) > CACHE_DURATION ||
        this.needsRefreshForDate(selectedDate)) {
      this.loadTodayEntryListWithOptimization();
    } else {
    }
  },

  /**
   * 检查日期是否需要刷新数据
   */
  needsRefreshForDate(currentDate) {
    const cachedDate = this.data.dataCache.lastDate;
    return !cachedDate || cachedDate !== currentDate;
  },

  loadUserInfo() {
    const userInfo = wx.getStorageSync('userInfo') || { name: '系统管理员', employeeNumber: '001', account: '001' };
    this.setData({ userInfo });
  },

  initDate() {
    // 默认选择今天
    const today = new Date();
    const dateStr = `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`;
    this.setData({ selectedDate: dateStr });
  },

  // 日期选择
  onDateChange(e) {
    const selectedDate = e.detail.value;
    
    // 如果选择的日期和当前相同，不需要重新加载
    if (selectedDate === this.data.selectedDate) {
      return;
    }
    
    // 判断是否为今天，如果是今天则显示直报按钮，否则隐藏
    const today = new Date();
    const todayStr = `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`;
    const isToday = selectedDate === todayStr;
    
    this.setData({ 
      selectedDate,
      pageTitle: this.formatDateTitle(selectedDate),
      showDirectReportButton: isToday, // 只有选择今天时才显示直报按钮
      loading: true // 显示加载状态
    });
    
    // 防抖处理，避免频繁切换日期时重复请求
    this.debounceLoadData();
  },

  /**
   * 防抖加载数据
   */
  debounceLoadData() {
    if (this.loadDataTimer) {
      clearTimeout(this.loadDataTimer);
    }
    
    this.loadDataTimer = setTimeout(() => {
      this.loadTodayEntryListWithOptimization();
    }, 300); // 300ms防抖
  },

  // 格式化页面标题
  formatDateTitle(dateStr) {
    if (!dateStr) return '今日录入';
    
    try {
      const today = new Date();
      const selectedDate = new Date(dateStr);
      const todayStr = `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`;
      
      if (dateStr === todayStr) {
        return '今日录入';
      } else {
        const month = selectedDate.getMonth() + 1;
        const day = selectedDate.getDate();
        return `${month}月${day}日录入`;
      }
    } catch (error) {
      return '录入详情';
    }
  },

  /**
   * 优化版数据加载 - 包含缓存机制
   */
  async loadTodayEntryListWithOptimization() {
    const { selectedDate, userInfo, dataCache } = this.data;
    const cacheKey = `${selectedDate}_${userInfo?.employeeNumber || userInfo?.account}`;
    
    // 检查缓存
    if (dataCache[cacheKey] && !this.isCacheExpired(dataCache[cacheKey].timestamp)) {
      const { entryList, statistics } = dataCache[cacheKey];
      this.setData({ 
        entryList, 
        statistics,
        loading: false 
      });
      
      return;
    }
    
    // 缓存失效或不存在，重新加载
    await this.loadTodayEntryList();
  },

  /**
   * 检查缓存是否过期
   */
  isCacheExpired(timestamp) {
    const CACHE_DURATION = 2 * 60 * 1000; // 2分钟
    return Date.now() - timestamp > CACHE_DURATION;
  },

  // 加载今日录入列表
  async loadTodayEntryList() {
    const { selectedDate, userInfo } = this.data;
    
    
    // 获取员工账号，优先使用employeeNumber字段，如果没有则使用account
    const employeeAccount = userInfo?.employeeNumber || userInfo?.account;
    
    if (!employeeAccount) {
      
      wx.showToast({
        title: '用户信息不完整',
        icon: 'none'
      });
      return;
    }

    this.setData({ loading: true });

    try {
      const result = await getTodayEntryList(selectedDate, employeeAccount);
      
      if (result.message == "操作成功") {
        
        // 格式化数据
        const entryList = this.formatEntryList(result.data);
        const statistics = this.calculateStatistics(entryList);
        
        
        // 更新缓存
        const cacheKey = `${selectedDate}_${userInfo?.employeeNumber || userInfo?.account}`;
        const cacheData = {
          entryList,
          statistics,
          timestamp: Date.now()
        };
        
        this.setData({ 
          entryList,
          statistics,
          lastLoadTime: Date.now(),
          [`dataCache.${cacheKey}`]: cacheData,
          [`dataCache.lastDate`]: selectedDate
        });
        
        
      } else {

        wx.showToast({
          title: result.message || '获取数据失败',
          icon: 'none'
        });
      }
    } catch (error) {

      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 格式化录入列表数据
  formatEntryList(data) {
    
    // API返回的是扁平化的数组结构，直接处理
    if (!data || !Array.isArray(data)) {
      return [];
    }

    const entryList = data.map(item => {
      
      return {
        id: item.id || `${item.employeeNumber}_${item.productCode}_${item.processNumber}`,
        employeeName: item.employeeName,
        employeeAccount: item.employeeNumber,
        productName: item.productName,
        productCode: item.productCode,
        processName: item.processName,
        processCode: item.processNumber || item.processCode, // 兼容两种字段名
        quantity: item.quantity,
        unitPrice: parseFloat(item.price || 0).toFixed(2),
        totalAmount: parseFloat(item.totalAmount || 0).toFixed(2),
        status: this.getProcessStatus(item.isChecked),
        createTime: this.formatTime(item.createTime),
        checkTime: this.formatTime(item.checkTime),
        checker: item.checker,
        remark: item.remark
      };
    });

    return entryList;
  },

  // 获取工序状态
  getProcessStatus(isChecked) {
    switch (isChecked) {
      case 0:
        return 'pending'; // 待审核
      case 1:
        return 'approved'; // 已通过
      case 2:
        return 'rejected'; // 已拒绝
      default:
        return 'pending';
    }
  },

  // 计算统计信息
  calculateStatistics(entryList) {
    const statistics = {
      totalCount: entryList.length,
      totalAmount: '0.00',
      approvedCount: 0,
      pendingCount: 0,
      rejectedCount: 0
    };

    let totalAmount = 0;

    entryList.forEach(item => {
      totalAmount += parseFloat(item.totalAmount || 0);
      
      switch (item.status) {
        case 'approved':
          statistics.approvedCount++;
          break;
        case 'pending':
          statistics.pendingCount++;
          break;
        case 'rejected':
          statistics.rejectedCount++;
          break;
      }
    });

    statistics.totalAmount = totalAmount.toFixed(2);
    
    return statistics;
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'pending': '待审核',
      'approved': '已通过',
      'rejected': '已拒绝'
    };
    return statusMap[status] || '未知';
  },

  // 格式化时间
  formatTime(timeString) {
    if (!timeString) return '';
    
    try {
      const date = new Date(timeString);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    } catch (error) {
      return timeString;
    }
  },

  // 刷新数据
  onRefresh() {
    // 清除缓存，强制重新加载
    const { selectedDate, userInfo } = this.data;
    const cacheKey = `${selectedDate}_${userInfo?.employeeNumber || userInfo?.account}`;
    
    this.setData({
      [`dataCache.${cacheKey}`]: null,
      loading: true
    });
    
    this.loadTodayEntryList();
  },

  // 查看详情
  onViewDetail(e) {
    const { item } = e.currentTarget.dataset;
    this.setData({
      selectedItem: item,
      showDetailModal: true
    });
  },

  // 关闭详情弹窗
  closeDetailModal() {
    this.setData({
      showDetailModal: false,
      selectedItem: null
    });
  },

  // 下拉刷新
  async onPullDownRefresh() {
    // 清除当前日期的缓存
    const { selectedDate, userInfo } = this.data;
    const cacheKey = `${selectedDate}_${userInfo?.employeeNumber || userInfo?.account}`;
    
    this.setData({
      [`dataCache.${cacheKey}`]: null
    });
    
    await this.loadTodayEntryList();
    wx.stopPullDownRefresh();
  },

  // 页面卸载时清理资源
  onUnload() {
    // 清理定时器
    if (this.loadDataTimer) {
      clearTimeout(this.loadDataTimer);
      this.loadDataTimer = null;
    }
    
    // 清理缓存（可选，根据需要决定是否保留）
    // this.setData({ dataCache: {} });
    
  },

  // 返回上一页
  navigateBack() {
    const { fromPage } = this.data;
    
    // 根据来源页面进行智能返回
    if (fromPage === 'salary-query') {
      // 从工资查询页面跳转过来的，返回到工资查询页面
      wx.navigateTo({
        url: 'pages/salary-query/salary-query',
      })
  
    } else {
      // 其他情况或直接进入的页面，使用默认返回逻辑
      wx.navigateBack({
        delta: 1,
        success: () => {
        },
        fail: (err) => {
  
          wx.switchTab({
            url: '/pages/workbench/workbench'
          });
        }
      });
    }
  },

  // 跳转到员工直报页面
  goToPieceworkEntry() {
    wx.navigateTo({
      url: '/pages/piecework-entry/piecework-entry'
    });
  }
}); 